package com.mate.cloud.pipeline.coderiver.service.impl;

import com.alibaba.fastjson2.JSON;
import com.google.common.collect.Lists;
import com.mate.cloud.core.util.CollectionUtils;
import com.mate.cloud.pipeline.coderiver.dto.UserDTO;
import com.mate.cloud.pipeline.coderiver.entity.User;
import com.mate.cloud.pipeline.coderiver.service.RedisPipelineService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.List;

@Slf4j
@Service
public class RedisPipelineServiceImpl implements RedisPipelineService {

    @Resource
    private RedisTemplate redisTemplate;


    @Override
    public long batchInsertWithPipeline(String prefix, int count) {
        long startTime = System.currentTimeMillis();

        // 执行 Pipeline 操作
        redisTemplate.executePipelined((RedisCallback<Object>) connection -> {
            // 批量添加命令到 Pipeline
            for (int i = 0; i < count; i++) {
                String key = prefix + ":" + i;
                String value = "value:" + i;
                // 添加 SET 命令到管道（不立即执行）
                connection.set(key.getBytes(), value.getBytes());
            }
            // Pipeline 不需要返回值，返回 null 即可
            return null;
        });

        long endTime = System.currentTimeMillis();
        return endTime - startTime;
    }

    @Override
    public long batchInsertWithout(String prefix, int count) {
        long startTime = System.currentTimeMillis();

        // 逐条插入（性能差）
        for (int i = 0; i < count; i++) {
            String key = prefix + ":" + i;
            String value = "value:" + i;
            redisTemplate.opsForValue().set(key, value);
        }

        long endTime = System.currentTimeMillis();
        return endTime - startTime;
    }

    @Override
    public void batchUserPipeline(String prefix, Integer count) {
        long startTime = System.currentTimeMillis();
        List<UserDTO> users = this.users(count);

        cacheRssNews(prefix, users);
        long endTime = System.currentTimeMillis();
        long time= (endTime - startTime);

        log.info("Pipeline批量添加完成时间:{} 毫秒",time);
    }


    private List<UserDTO> users(Integer num) {
        List<UserDTO> userDTOList = Lists.newArrayList();
        for (int i=0; i < num; i++) {

            UserDTO userDTO = new UserDTO();
            userDTO.setId(i);
            userDTO.setName("name:" + i);

            userDTOList.add(userDTO);
        }
        return userDTOList;
    }
    /**
     * 数据缓存
     *
     * @param userDTOList
     */
    private void cacheRssNews(String redisKey, List<UserDTO> userDTOList) {

        if (CollectionUtils.isEmpty(userDTOList)) {
            return;
        }

        redisTemplate.delete(redisKey);
        log.info("############################################################");
        log.info("初始化rss新闻到redis中,size:{}", userDTOList.size());
        byte[] keyBytes = redisKey.getBytes(StandardCharsets.UTF_8);
        redisTemplate.executePipelined((RedisCallback<User>) redisConnection -> {
            redisConnection.openPipeline();
            for (UserDTO rssNewsDTO : userDTOList) {
                redisConnection.lPush(keyBytes, JSON.toJSONString(rssNewsDTO).getBytes(StandardCharsets.UTF_8));
            }
            redisConnection.closePipeline();
            return null;
        });
        log.info("初始化完成,key:{}", redisKey);
        log.info("############################################################");

    }
}
